package com.hmall.item.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.pojo.dto.ItemDto;
import com.hmall.item.pojo.vo.ItemVo;
import com.hmall.item.service.IItemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Objects;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    @GetMapping("/list")
    public PageDTO<Item> findItemsByPage(@RequestParam("page") Integer page,@RequestParam("size") Integer size){
        return itemService.findItemsByPage(page,size);
    }

    @GetMapping("/{id}")
    public ItemVo findItemById(@PathVariable("id") Long id){
        if (Objects.isNull(id)){
            return null;
        }
        Item item = itemService.getById(id);
        ItemVo itemVo = ItemVo.builder().build();
        BeanUtils.copyProperties(item, itemVo);
        return itemVo;
    }

    @PostMapping
    public void addItem(@RequestBody ItemDto itemDto){
        itemService.addItem(itemDto);
    }

    @PutMapping("/status/{id}/{status}")
    public void updateItemSaleStatus(@PathVariable("id") Long id,@PathVariable("status") Integer status){
        if (Objects.isNull(id) || Objects.isNull(status)){
            return;
        }
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        itemService.updateById(item);
    }

    @PutMapping
    public void updateItemById(@RequestBody ItemDto itemDto){
        if (Objects.isNull(itemDto)){
            return;
        }
        Item item = new Item();
        BeanUtils.copyProperties(itemDto,item);
        itemService.updateById(item);
    }

    @DeleteMapping("/{id}")
    public void deleteItemById(@PathVariable("id") Long id){
        if (Objects.isNull(id)){
            return;
        }
        itemService.removeById(id);
    }
}
